
const CryptoJS = require('crypto-js');
const KEY_PWD = process.env.DES_CMS_KEY;

export function encryptUrl(input) {
    let CIPHER_ALGORITHM = "DES-CBC";
    let IV_SIZE = 8;
    let KEY_PWD = process.env.DES_CMS_KEY;
    try {
      const keyBytes = CryptoJS.enc.Utf8.parse(KEY_PWD);
      const inputBytes = CryptoJS.enc.Utf8.parse(input);
      const ivBytes = CryptoJS.lib.WordArray.random(IV_SIZE);
      const encrypted = CryptoJS.DES.encrypt(inputBytes, keyBytes, {
        iv: ivBytes,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      });
      const ciphertext = ivBytes.concat(encrypted.ciphertext);
      return ciphertext.toString();
    } catch (error) {
      console.error(error);
      return null;
    }
}
 




export function decryptUrl(cipherText ) {
    let CIPHER_ALGORITHM = "DES-CBC";
    let IV_SIZE = 8;
    let KEY_PWD = process.env.DES_CMS_KEY;
    try {
      let keyBytes = CryptoJS.enc.Utf8.parse(
        KEY_PWD.padEnd(CIPHER_ALGORITHM === "DES-CBC" ? 8 : 16)
      );
      let ivBytes = { iv: CryptoJS.enc.Hex.parse(process.env.DES_CMS_IV) }; // 如果使用CBC模式，需要一个初始化向量iv，这里是空向量
      let decrypted = CryptoJS.DES.decrypt(
        { ciphertext: CryptoJS.enc.Hex.parse(cipherText) },
        keyBytes,
        ivBytes
      );
      return decrypted.toString(CryptoJS.enc.Utf8);
    } catch (e) {
      console.error(e);
      return null;
    }
}